//
//  AMapHandler.swift
//  TestWorkSpace
//
//  Created by Mac on 2020/1/7.
//  Copyright © 2020 jhf. All rights reserved.
//

import UIKit

import AMapFoundationKit
import AMapLocationKit
import AMapSearchKit

import CooperSwift

enum AMapLocationType {
    case defaultInfo
    case locationInfo
    case chooseInfo
    /// 返回对应vaue
    func stringValue() -> String{
        switch self {
        case .chooseInfo:
            return "AMapInfoChooseInfo"
        case .locationInfo:
            return "AMapInfoLocationInfo"
        default:
            return "AMapInfoDefaultInfo"
        }
    }
}

class AMapLocationInfo : JSONProtocol, Codable {
    
    var latitude: Double? /// 经纬度
    var longitude: Double? /// 经纬度
    var cityId: String? /// city Id
    var provinceId: String? /// province Id
    
    var formattedAddress: String? /// 格式化地址
    var country: String? /// 国家
    var province: String? /// 省/直辖市
    var city: String? /// 市
    var district: String? /// 区
    var citycode: String? /// 城市编码
    var adcode: String? /// 区域编码
    var street: String? /// 街道名称
    var number: String? /// 门牌号
    var poiName: String? /// 兴趣点名称
    var aoiName: String? /// 所属兴趣点名称

    // 特别傻
    init(_ regeocode: AMapLocationReGeocode) {
        self.formattedAddress = regeocode.formattedAddress
        self.country = regeocode.country
        self.province = regeocode.province
        self.city = regeocode.city
        self.district = regeocode.district
        self.citycode = regeocode.citycode
        self.adcode = regeocode.adcode
        self.street = regeocode.street
        self.number = regeocode.number
        self.poiName = regeocode.poiName
        self.aoiName = regeocode.aoiName
    }
    
    /// 显示默认位置 选择>定位>默认
    class func show() -> AMapLocationInfo? {
        if let value = AMapLocationInfo.show(type: .chooseInfo) {
            return value
        }
        if let value = AMapLocationInfo.show(type: .locationInfo) {
            return value
        }
        if let value = AMapLocationInfo.show(type: .defaultInfo) {
            return value
        }
        return nil
    }
    
    /// 显示位置
    /// - Parameter type: 位置类型
    class func show(type: AMapLocationType) -> AMapLocationInfo? {
        guard let value = UserDefaults.standard.object(forKey: type.stringValue()) else {
            return nil
        }
       
        if let val = value as? String {
            let decodedData = try? JSONDecoder().decode(AMapLocationInfo.self, from: val.data(using: .utf8)!)
            log.debug(decodedData?.toJSONString() ?? "")
            return decodedData
        }
        return nil
    }
    
    func update(type: AMapLocationType) {
        UserDefaults.standard.set(self.toJSONString(), forKey: type.stringValue())
        UserDefaults.standard.synchronize()
    }
    
    func remove(type: AMapLocationType) {
        UserDefaults.standard.removeObject(forKey: type.stringValue())
        UserDefaults.standard.synchronize()
    }
    
}

class AMapHandler: NSObject {
    
    lazy var locationManager: AMapLocationManager = {
        let manager = AMapLocationManager()
        manager.desiredAccuracy = kCLLocationAccuracyHundredMeters
        manager.locationTimeout = 10
        manager.reGeocodeTimeout = 10
        return manager
    }()
    
    static let shared = AMapHandler()
    
    /// 配置高德
    func configAMap() {
        AMapServices.shared()?.enableHTTPS = true
        AMapServices.shared()?.apiKey = "cdad10edcd0982e2ac3e544f28042664"
        startLocation()
    }
    
    /// 获取位置信息
    func startLocation(result: ((Bool)->Void)? = nil) {
        /// 检查权限
        AuthCheckHandler.shared.hw_openLocationServiceWithBlock(true) { [weak self] (res) in
            if res { /// 获取权限成功
                self?.locationManager.requestLocation(withReGeocode: true) { (location, regeocode, error) in
                    if (error == nil) {
                        let info = AMapLocationInfo(regeocode!)
                        info.latitude = location?.coordinate.latitude
                        info.longitude = location?.coordinate.longitude
                        info.update(type: .locationInfo)
                        if result != nil {result!(true)}
                        return
                    }
                    if result != nil {result!(false)}
                }
            }else {
                if result != nil {result!(false)}
            }
        }
        
    }
    
}
